package org.luxor.cloud.users.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.luxor.commons.core.exception.BaseException;
import org.luxor.commons.core.web.RestStatus;
import org.luxor.commons.core.web.controller.BaseRestController;
import org.luxor.commons.core.web.data.R;
import org.luxor.commons.security.entity.UserSubject;
import org.luxor.commons.security.utils.SecurityUtils;
import org.luxor.system.security.UserDetailsService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;

/**
 * 认证用户详情信息
 *
 * @author Mr.Yan  @date: 2020/10/11
 */
@RestController
@Api(tags = "用户")
@RequestMapping("userDetails")
public class UserDetailsController extends BaseRestController {

    @Resource
    private UserDetailsService userDetailsService;

    @ApiIgnore
    @ApiOperation("根据用户名获取账号详情信息")
    @ApiImplicitParam(name = "username", value = "登陆账号", paramType = "path", required = true)
    @GetMapping("/loadUserByUsername/{username}")
    @PreAuthorize("#oauth2.hasAnyScope('user_details')")
    public R<UserSubject> loadUserByUsername(@PathVariable("username") String username) {
        try {
            UserSubject userSubject = (UserSubject) userDetailsService.loadUserByUsername(username);
            return R.ok(userSubject);
        } catch (UsernameNotFoundException e) {
            logger.error("根据用户名获取账号详情信息，失败!", e);
            throw new BaseException(RestStatus.UNAUTHORIZED, e.getMessage());
        }
    }

    @ApiIgnore
    @GetMapping("/user")
    public R<UserSubject> user() {
        return R.ok(SecurityUtils.getUser());
    }
}
